package com.integrate.redis.config.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘志强
 * @date 2020/12/1 10:47
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    public RedisKeyExpirationListener(@Qualifier("redisMessageListenerContainer") RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    private static Map<String, MethodInterface> methodInterfaceMap = new HashMap<>();


    /**
     * 将key val存储至redis 并设置过期时间
     * 将methodInterface绑定至map中
     * @param key
     * @param val
     * @param millisecond
     * @param methodInterface
     * @return
     */
    public Boolean monitorSet(String key,String val,Long millisecond, MethodInterface methodInterface) {
        redisTemplate.opsForValue().set(key,val);
        Boolean aBoolean = redisTemplate.expire(key,millisecond, TimeUnit.MILLISECONDS);
        methodInterfaceMap.put(key,methodInterface);
        return aBoolean;
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        methodInterfaceMap.forEach((k,v) -> {
            if (k.equals(expiredKey)) {
                // 从map中去除对应的方法执行
                v.execute();
            }
        });
        // 清除map中的对象释放内存
        if (methodInterfaceMap.get(expiredKey) != null) {
            methodInterfaceMap.remove(expiredKey);
        }
    }
}
